{{/* Utterances 评论系统组件

  基于 GitHub Issues 的轻量级评论系统

  @context {page} . 当前文章页面对象
  @param {string} id 评论容器的唯一 ID
*/}}

{{ $id := .id | default "utterances-comments" }}
{{ $config := .Site.Params.comments.utterances }}

{{ if $config.repo }}
  <div id="{{ $id }}" class="utterances-container">
    <script
      src="https://utteranc.es/client.js"
      repo="{{ $config.repo }}"
      issue-term="{{ $config.issueTerm | default "pathname" }}"
      label="{{ $config.label | default "comment" }}"
      theme="{{ $config.theme | default "preferred-color-scheme" }}"
      crossorigin="anonymous"
      async></script>
  </div>

  {{/* 主题切换支持 */}}
  <script>
    (function() {
      'use strict';

      // 监听主题变化
      function updateUtterancesTheme() {
        const iframe = document.querySelector('#{{ $id }} .utterances-frame');
        if (!iframe) return;

        // 获取当前主题
        const isDark = document.documentElement.classList.contains('dark');
        const theme = isDark ? 'github-dark' : 'github-light';

        // 发送主题更新消息
        iframe.contentWindow.postMessage({
          type: 'set-theme',
          theme: theme
        }, 'https://utteranc.es');
      }

      // 监听主题切换事件
      document.addEventListener('themeChanged', updateUtterancesTheme);

      // 监听 DOM 变化（用于检测主题切换）
      const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
            updateUtterancesTheme();
          }
        });
      });

      observer.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ['class']
      });
    })();
  </script>
{{ else }}
  <div id="{{ $id }}" class="py-8 text-center">
    <div
      class="bg-muted/50 mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full">
      {{ partial "features/icon.html" (dict "name" "github" "size" "lg" "ariaLabel" "") }}
    </div>
    <h3 class="text-foreground mb-2 text-lg font-medium">
      {{ i18n "comments.utterances_not_configured" | default "Utterances 未配置" }}
    </h3>
    <p class="text-muted-foreground text-sm">
      {{ i18n "comments.utterances_config_desc" | default "请在站点配置中设置 GitHub 仓库信息" }}
    </p>
  </div>
{{ end }}
